package com.starnet.yarnmonitor.yarn.utils;


import com.starnet.yarnmonitor.yarn.conf.YarnConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
@Component
public class HttpUtils {
    //获取所有节点的官方restful api
    public static final String NODES_URL ="/ws/v1/cluster/nodes";
    //获取集群概述的官方restful api
    public static final String METRICS_URL = "/ws/v1/cluster/metrics";
    @Autowired
    YarnConf yarnConf;
    public String get(String url) throws IOException {
        String urlStart = "http://"+yarnConf.getHost()+":"+yarnConf.getPort();
        String urlToSend = urlStart+url;
        URL serverUrl = new URL(urlToSend);
        HttpURLConnection conn = (HttpURLConnection) serverUrl.openConnection();
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Content-type", "application/json");
        //必须设置false，否则会自动redirect到重定向后的地址
        conn.setInstanceFollowRedirects(false);
        conn.connect();
        String result = getReturn(conn);
        return result;
    }

    /*请求url获取返回的内容*/
    public static String getReturn(HttpURLConnection connection) throws IOException {
        StringBuffer buffer = new StringBuffer();
        //将返回的输入流转换成字符串
        try (InputStream inputStream = connection.getInputStream();
             InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
             BufferedReader bufferedReader = new BufferedReader(inputStreamReader);) {
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            String result = buffer.toString();
            return result;
        }

    }
}
